﻿@model IEnumerable<JewererBasic.Models.ServiceTool>


@{
    ViewBag.Title = "Import Tool";

    var gd = new WebGrid(
            Model,
            canPage: true,
            rowsPerPage: 10,
            selectionFieldName: "selectedRow",
            ajaxUpdateContainerId: "gridContent"
        );
    gd.Pager(WebGridPagerModes.NextPrevious);
}

<h2>Import Tool</h2>

@using (Html.BeginForm())
{
    <fieldset>
        <div>
            <a href="/Tool/Index">
                <input type="button" value="BACK" />
            </a>
        </div>

        <div>
            <table>
                <tr>
                    <td>
                        <fieldset>
                            <legend>IMPORTED INFORMATION</legend>
                            <table>
                                <tr>
                                    <td style="width: 500px;"><b>Exporter: </b>@ViewBag.CurrentUser</td>
                                    <td style="width: 500px;"><b>Date: </b>@ViewBag.CurrentDate</td>
                                </tr>
                            </table>
                        </fieldset>
                    </td>
                </tr>
                <tr>
                    <td>
                        <fieldset>
                            <legend>TOOLs</legend>
                            <table id="ToolAdd">
                                <tr>
                                    <td style="text-align: center">
                                        <strong>Item</strong>
                                    </td>
                                    <td style="text-align: center">
                                        <strong>Quantity</strong>
                                    </td>
                                    <td style="text-align: center">
                                        <strong>Price</strong>
                                    </td>
                                    <td style="text-align: center">
                                        <strong>Reason</strong>
                                    </td>
                                     
                                </tr>
                                <tr>
                                    <td>@Html.TextBox("txtId", "", new { title = "Input id.", placeholder = "Tool Id.", style = "width: 200px;" })</td>
                                    <td>@Html.TextBox("txtQuantity", "", new { type = "number", min = "0", @class = "inputItem", title = "Input quantity.", placeholder = "Quantity" })</td>
                                    <td>@Html.TextBox("txtPrice", "", new { type = "number", min = "0", @class = "inputItem", title = "Input price.", placeholder = "Price" })</td>
                                    <td>@Html.TextBox("txtReason", "", new { title = "Reason", placeholder = "Reason", style = "width: 200px;" })</td>
                                    <td>
                                        <input type="button" value="ADD" id="submitAdd" /></td>
                                </tr>
                                <tr>
                                    <td colspan="3" style="height: 25px;"><span id="errorNotification" style="display: none; color: red"></span></td>
                                </tr>
                            </table>

                            <div id="ToolPanel" style="display: none; width: 660px;">
                                    <div id="ToolListDiv">
                                        @gd.GetHtml(
                                        tableStyle: "table",
                                        headerStyle: "head",
                                        rowStyle: "row",
                                        alternatingRowStyle: "altRow",
                                        selectedRowStyle: "selectRow",
                                        columns: gd.Columns(
                                        gd.Column(header: "Tool", format: @<div style="width: 200px; text-align: center;"><span><span id="spanId_@item.Id">@item.Id</span></span></div>),
                                        gd.Column(header: "Quantity", format: @<div style="width: 130px; text-align: center;"><span><span id="spanQuantity_@item.Id">@item.Quantity</span>@Html.TextBox("Quantity_" + (string)item.Id, (int)item.Quantity, new { @style = "display:none; width: 120px", @type = "number", min = "0", @class = "inputItem" })</span></div>),
                                        gd.Column(header: "Price", format: @<div style="width: 130px; text-align: center;"><span><span id="spanPrice_@item.Id">@item.Price</span>@Html.TextBox("Price_" + (string)item.Id, (int)item.Price, new { @style = "display:none; width: 120px", @type = "number", min = "0", @class = "inputItem" })</span></div>),
                                        gd.Column(header: "Total Cost", format: @<div style="width: 130px; text-align: center;"><span><span id="spanTotalCost_@item.Id">@item.Price</span></span></div>),
                                        gd.Column(header: "Reason", format: @<div style="width: 200px; text-align: center;"><span><span id="spanReason_@item.Id">@item.Reason</span>@Html.TextBox("Reason_" + (string)item.Id, (string)item.Reason, new { @style = "display:none; width: 170px" })</span></div>),
                                        gd.Column(header: "Action", format: @<div style="width: 200px; text-align: center;"><a href="#" id="Edit_@item.Id" style="margin: 5px" class="edit">Edit</a><a href="#" id="Update_@item.Id" style="display:none; margin: 5px" class="update">Update</a><a href="#" id="Cancel_@item.Id" style="display:none; margin: 5px" class="cancel">Cancel</a><a href="#" id="Delete_@item.Id" style="margin: 5px" class="delete">Delete</a></div>)
                                    ))
                                    </div>
                            </div>
                        </fieldset>
                    </td>
                </tr>
            </table>
        </div>

        <div>
            <input type="button" name="submit" id="submitFinish" value="FINISH" />
            <input type="button" id="submitClear" value="CLEAR" />
        </div>
    </fieldset>
}


@section Scripts {

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script src="@Url.Content("~/Scripts/json2.min.js")" type="text/javascript"></script>
    <script type="text/javascript">

        $(function () {
            window.alert = function (message) {
                $(document.createElement('div'))
                    .attr({ title: 'Information', 'class': 'alert' })
                    .html(message)
                    .dialog({
                        buttons: { OK: function () { $(this).dialog('close'); } },
                        close: function () { $(this).remove(); },
                        draggable: true,
                        modal: true,
                        resizable: false,
                        width: 'auto'
                    });
            };
        });

        $("#txtId, #txtQuantity, #txtPrice").keypress(function (e) {
            if (e.keyCode == 13) {
                e.preventDefault();
            }
        });

        $("#submitClear").click(function () {

            $("#ToolPanel").hide();

            $("#txtId").val("");
            $("#txtQuantity").val("");
            $("#txtPrice").val("");
            $("#txtReason").val("");

            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: '/Tool/ClearImportForm',
                dataType: "json",
                beforeSend: function () {
                },
                success: function (data) {
                    $("#txtId").focus();
                    $("#ToolListDiv").find("table").find("tbody").empty();
                }
            });
        });

        $("#submitFinish").click(function () {
            var numberOfRecords = $("#ToolListDiv tbody").children().length;

            if (numberOfRecords == 0) {
                $("#errorNotification").text("Cannot complete the import because the imported item list is empty.").show().fadeOut(5000);
                return false;
            } else {
                //$("form").submit();
                $.ajax({
                    url: '/Tool/SaveImport',
                    data: {},
                    dataType: 'json',
                    type: 'GET',
                    success: function (data) {
                        var text = "";
                        text += '<a href="/Report/ImportedTool?id=' + data.id + '"><input type="button" id="submitPrint" value="PRINT" /></a>';

                        //$("#submitFinish").parent().html(text);
                        $("#ToolAdd").hide();
                        alert("Import Tool successfully.");
                        $("#submitFinish").hide();
                    },
                    error: function (xhr, errorType, exception) {

                    }
                });
            }
        });

        $("#txtId").blur(function () {
            var id = $(this).val();

            $.ajax({
                url: '/Tool/IsToolExisted',
                data: { "id": id },
                dataType: 'json',
                type: 'GET',
                success: function (data) {
                    if (data.result == false) {
                        $("#errorNotification").text("Tool id hasn't existed in the system yet.").show();
                    }
                },
                error: function (xhr, errorType, exception) {

                }
            });
        });

        $("#submitAdd").click(function () {

            $("#ToolPanel").show();

            var id = $("#txtId").val();
            var quantity = $("#txtQuantity").val();
            var price = $("#txtPrice").val();
            var reason = $("#txtReason").val();

            if (id.length == 0 || quantity.length == 0 || price.length == 0) {
                $("#errorNotification").text("Please fill all fields.").show();
            } else {
                $.ajax({
                    url: '/Tool/IsToolExisted',
                    data: { "id": id },
                    dataType: 'json',
                    type: 'GET',
                    success: function (data) {
                        if (data.result == false) {
                            $("#errorNotification").text("Tool id hasn't existed in the system yet.").show();
                            $("#txtId").focus();
                        } else {
                            $.ajax({
                                url: '/Tool/AddImport',
                                data: { "id": id, "quantity": quantity, "price" : price, "reason": reason },
                                dataType: 'json',
                                type: 'GET',
                                success: function (data) {
                                    if (data.result == true) {
                                        //$("#errorNotification").text("Import Tool successfully.").show().fadeOut(5000);

                                        var className = $("#ToolListDiv").find("tbody").find("tr:last").hasClass("row");

                                        if (className == true) {
                                            className = "altRow";
                                        } else {
                                            className = "row";
                                        }

                                        var totalCost = parseInt(quantity) * parseInt(price);

                                        var newRow = '<tr class="' + className + '"><td><div id="spanId_' + id + '" style="width: 200px; text-align: center;">' + id + '</div></td>'
                                            + '<td><div style="width: 130px; text-align: center;"><span id="spanQuantity_' + id + '">' + quantity + '</span><input id="Quantity_' + id + '" style="display:none; width: 120px" type="text" value="' + quantity + '"></div></td>'
                                            + '<td><div style="width: 130px; text-align: center;"><span id="spanPrice_' + id + '">' + price + '</span><input id="Price_' + id + '" style="display:none; width: 120px" type="text" value="' + price + '"></div></td>'
                                            + '<td><div style="width: 130px; text-align: center;"><span id="spanTotalCost_' + id + '">' + totalCost + '</span></div></td>'
                                            + '<td><div style="width: 200px; text-align: center;"><span id="spanReason_' + id + '">' + reason + '</span><input id="Reason_' + id + '" style="display:none; width: 170px" type="text" value="' + reason + '"></div></td>'
                                            + '<td><div style="width: 200px; text-align: center;"><a href="#" id="Edit_' + id + '" style="margin: 5px" class="edit">Edit</a><a href="#" id="Update_' + id + '" style="display:none; margin: 5px" class="update">Update</a><a href="#" id="Cancel_' + id + '" style="display:none; margin: 5px" class="cancel">Cancel</a><a href="#" id="Delete_' + id + '" style="margin: 5px" class="delete">Delete</a></div></td>' + "</tr>";

                                        $("#ToolListDiv").find("table tbody:last").append(newRow);

                                        $("#txtId").val("");
                                        $("#txtQuantity").val("");
                                        $("#txtPrice").val("");
                                        $("#txtReason").val("");
                                    }
                                },
                                error: function (xhr, errorType, exception) {
                                    $("#errorNotification").text("Some unexpected error occurred.").show().fadeOut(5000);
                                }
                            });
                        }
                    },
                    error: function (xhr, errorType, exception) {

                    }
                });
            }
        });

        $("#txtId").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '/Tool/GetTools',
                    data: { query: request.term },
                    dataType: 'json',
                    type: 'GET',
                    success: function (data) {
                        response($.map(data, function (item) {
                            return {
                                label: item,
                                value: item
                            }
                        }));
                    },
                })
            },
            messages: {
                noResults: '',
                results: function () { }
            },
            select: function (event, ui) {
                $("#txtId").val(ui.item.label);
                return false;
            },
            minLength: 1
        });

        $("#txtQuantity").blur(function () {
            var value = $(this).val();
            var valueNumber = parseFloat(value);

            if (valueNumber <= 0) {
                $(this).focus();
                $("#errorNotification").text("This is only bigger than 0.").show().fladOut(5000);
            }
        });

        jQuery(".inputItem").keydown(function (event) {
            // Allow: backspace, delete, tab, escape, enter and .
            if (jQuery.inArray(event.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
                // Allow: Ctrl+A
                (event.keyCode == 65 && event.ctrlKey === true) ||
                // Allow: home, end, left, right
                (event.keyCode >= 35 && event.keyCode <= 40)) {

                return;
            }
            else {
                // Ensure that it is a number and stop the keypress
                if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                    event.preventDefault();
                }
                else {
                    var $focused = $(':focus');
                    if ($focused.val().length >= 10) {
                        $focused.keydown(function (event) {
                            event.preventDefault();
                        })
                    }
                }
            }
        });

        $(document).on("click", ".edit", function () {
            var str = $(this).attr("id").split("_");
            id = str[1];

            var spanQuantity = "#spanQuantity_" + id;
            var Quantity = "#Quantity_" + id;
            var spanPrice = "#spanPrice_" + id;
            var Price = "#Price_" + id;
            var spanReason = "#spanReason_" + id;
            var Reason = "#Reason_" + id;

            $(Quantity).val($(spanQuantity).text());
            $(Price).val($(spanPrice).text());
            $(Reason).val($(spanReason).text());

            $(spanQuantity).hide();
            $(Quantity).show();
            $(spanPrice).hide();
            $(Price).show();
            $(spanReason).hide();
            $(Reason).show();

            $(this).hide();
            $("#Update_" + id).show();
            $("#Cancel_" + id).show();

            return false;
        });

        $(document).on("click", ".update", function () {
            var str = $(this).attr("id").split("_");
            id = str[1];

            var quantityVal = $("#Quantity_" + id).val();
            var priceVal = $("#Price_" + id).val();
            var reasonVal = $("#Reason_" + id).val();

            if (id != "") {
                $.ajax({
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    url: '@Url.Action("UpdateImportTool", "Tool")',
                    data: { "id": id, "quantity": quantityVal, "price": priceVal, "reason": reasonVal },
                    dataType: "json",
                    beforeSend: function () {//alert(id);
                    },
                    success: function (data) {
                        if (data.result == true) {
                            $("#Update_" + id).hide();
                            $("#Cancel_" + id).hide();
                            $("#Edit_" + id).show();

                            var spanQuantity = "#spanQuantity_" + id;
                            var Quantity = "#Quantity_" + id;
                            var spanPrice = "#spanPrice_" + id;
                            var Price = "#Price_" + id;
                            var spanTotalCost = "#spanTotalCost_" + id;
                            var spanReason = "#spanReason_" + id;
                            var Reason = "#Reason_" + id;

                            $(Quantity).hide();
                            $(spanQuantity).show();
                            $(Price).hide();
                            $(spanPrice).show();
                            $(Reason).hide();
                            $(spanReason).show();

                            $(spanQuantity).text($(Quantity).val());
                            $(spanPrice).text($(Price).val());
                            $(spanTotalCost).text(parseInt($(Price).val()) * parseInt($(Quantity).val()));
                            $(spanReason).text($(Reason).val());
                        }
                        else {
                            alert('There is some error');
                        }
                    }
                });
            }

            return false;
        });

        $(document).on("click", ".delete", function () {
            var str = $(this).attr("id").split("_");
            id = str[1];

            if (id != "") {
                $.ajax({
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    url: '@Url.Action("DeleteImportTool", "Tool")',
                    data: { "id": id },
                    dataType: "json",
                    beforeSend: function () { },
                    success: function (data) {
                        if (data.result == true) {
                            $("#Update_" + id).parentsUntil("tbody").remove();
                        } else {
                            alert('There is some error');
                        }
                    }
                });
            }

            return false;
        });

        $(document).on("click", ".cancel", function () {
            var str = $(this).attr("id").split("_");
            id = str[1];

            var spanQuantity = "#spanQuantity_" + id;
            var Quantity = "#Quantity_" + id;
            var spanPrice = "#spanPrice_" + id;
            var Price = "#Price_" + id;
            var spanReason = "#spanReason_" + id;
            var Reason = "#Reason_" + id;

            $(spanQuantity).show();
            $(Quantity).hide();
            $(spanPrice).show();
            $(Price).hide();
            $(spanReason).show();
            $(Reason).hide();

            $(this).hide();
            $("#Edit_" + id).show();
            $("#Update_" + id).hide();

            return false;
        });
    </script>
}